define(function(require, exports, module) {
	'use strict';
    
    var rk = require('rk');
    
    
    //
    //require('lib/fullcalendar/fullcalendar.min');
    //require('lib/fullcalendar/lang/zh-cn.rkhd');
    //require('./plus/fullCalendarPlus');
    var opener = require('./asset/opener');
    var scheduleService = require('scheduleService');
    //require('./plus/titleTab');
    //require('core/widgets/input/checkbox/widget');
    require('./asset/controllers/calOwnerSelCtrl');
    //require('./old/calEventTypeSelCtrl');
    //require('./old/calEventFilterCtrl');
    //require('./old/calGuiderCtrl');
    var rk_userService = require('userService');
    //这三个变量用于记录每个tab页当前选择的日期
    var currSelDay = "";
    var currSelWeek = "";
    var currSelMonth = "";

    //这三个变量用于记录每个tab页行头的年月
    var dayHead = "";
    var weekHead = "";
    var monthHead = "";

    //记录从哪个tab页切换过来的
    var fromTab = "";

    //记录切换tab页时日期是否可以找到匹配区间
    var match = false;

    //每个tab页设置的日期
    var tabDate;

    //记录查看哪个人的日程
    var userId;

    //用于记录上次点击日期
    var preClickDay;
    var preClickDayWeek;
    var preClickDayMonth;

    require('core/widgets/input/checkbox/widget.css');

    $.datepicker.constructor.prototype._markDatepicker = function(container, arDates) {
        var $cont = $(container),
            $tb = $cont.find('table.ui-datepicker-calendar');
        $cont.find('table.ui-datepicker-calendar').find('td span.circle').remove();
        if (arDates)
            $.each(arDates, function(i, d) {
                var $td = $tb.find('td[data-year="' + d.getFullYear() + '"][data-month="' + d.getMonth() + '"]');
                $td = $td.find('a').filter(function() {
                    return parseInt($(this).text(), 10) == d.getDate();
                }).parent();
                $td.size() && $td.addClass('ui-datepicker-marked') && $td.append('<span class="circle"></span>');
            });
    };

    var _generateHTML = $.datepicker.constructor.prototype._generateHTML;
    $.datepicker.constructor.prototype._generateHTML = function (inst) {
        var html = _generateHTML.call(this, inst);
        var firstDay = parseInt(this._get(inst, "firstDay"), 10);
        firstDay = (isNaN(firstDay) ? 0 : firstDay);
        var leadDays = (this._getFirstDayOfMonth(inst.drawYear, inst.drawMonth) - firstDay + 7) % 7;
        inst.firstDate = this._daylightSavingAdjust(new Date(inst.drawYear, inst.drawMonth, 1 - leadDays));
        var lastDate = new Date(inst.firstDate);
        lastDate.setDate(lastDate.getDate() + this.maxRows * 7);
        inst.lastDate = lastDate;
        return html;
    };

    $.widget('rk.schedulePanelCtrl', $.rk.oaPanelCtrl, {
        _create: function() {
            var me = this;
            var elem = me.element;
            me._initSchedulePanel();
            //initCalendar();
            //initCalendarHeader();
            //initCreateButton();
            //initData();
            //initGuider();
            //elem.on('click', 'div[applyId]', function () {
            //    me._handleRowClick($(this));
            //});
        },
        _init: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
        },
        _initSchedulePanel: function() {
            var me = this;
            var elem = me.element;
            var url = '/json/crm_schedule/index.action';
            rk.post(url, {}).done(function(json) {
                if (json.status == 0) {
                    me.$currentTimeMillis = json.data.currentTimeMillis;
                    me.salesParameterList = json.data.salesParameterList;   
                    rk_userService.loadRecentUserList(json);
                    scheduleService.setTypes(me.salesParameterList);
                    var html = rk.templateText(require('oa/tmpl/schedule/tpl_schedule_panel.tpl'), json.data);
                    elem.html(html);
                    elem.on('click','.oa-close-panel',function(){
                        rk.oa.closePanel();
                    });
                    //me._bindHandler();
                    var isIndustry = SESSION.tenantType;
                    if(isIndustry == 1){//判断是否是行业版
                        me._initCreateMenu();
                    }else{
                        me._bindHandler();
                    }
                    me._initOwnerSelecter();

                } else {
                    $.msg(rk.i18n('LOAD_ERROR'));
                }
            });
        },
        _initOwnerSelecter: function(){
            var me = this;
            var elem = me.element;
            var header = me.getPanelHeader();

            //console.log($('#ownerSelector').size())
            
            $('#ownerSelector').calOwnerSelCtrl({
                userId: '',
                onSelect: function(id, name){
                    //TODO: 加载日历
                    //alert('oc:'+id);
                    //变更时判断一下哪个处于激活态，传递激活的tab页重新加载数据
                    var scheduleDateTypes = elem.find('span[act=scheduleDateType]');
                    for (var i in scheduleDateTypes) {
                        if (scheduleDateTypes.eq(i).hasClass('active')) {
                            me._setUserId(id);
                            me._renderCalender(scheduleDateTypes.eq(i), true, undefined, true);
                            break;
                        }
                    }
                }
            });
            var uid = $('#ownerSelector').calOwnerSelCtrl('getUserId');
            //var uid = SESSION.user.id;

            //TODO: 加载日历
            //缺省加载第一个tab页的数据
            me._setUserId(SESSION.user.id);
            me._setDayHead(me.$currentTimeMillis);
            me._renderCalender(elem.find('span[act=scheduleDateType]').eq(0), true, me.$currentTimeMillis - 0);
            return uid;
        },
        _initCreateMenu: function () {
            var me = this;
            var elem = me.element;
            var header = me.getPanelHeader();
            header.find('[act="createSchedule"]').rkEasyMenu({
                menuId: "createScheduleMenu",
                onSelect: function (li) {
                    var act = li.attr('act');
                    //me._handleCreateClick(act);
                    me._handleCreateClick(act);
                }
            });
            me._bindHandler();
        },
        _setUserId: function (id){
            userId = id;
        },
        //用于左边日程页强制重新加载当前视图
        //export function
        reload: function (){
            var me = this;
            var elem = me.element;
            var scheduleDateTypes = elem.find('span[act=scheduleDateType]');
            for (var i in scheduleDateTypes) {
                if (scheduleDateTypes.eq(i).hasClass('active')) {
                    me._renderCalender(scheduleDateTypes.eq(i), true);
                    break;
                }
            }
        },
        _renderCalender:function(scheduleDateType, isForceLoad, fixedDate, userChange, noReloadLeft) {
            //console.log(scheduleDateType, isForceLoad, fixedDate, userChange)
            var me = this;
            var elem = me.element;
            var dateText = "";

            if(isForceLoad == undefined && scheduleDateType.hasClass('active')) {
                return false;
            }
            var viewType = scheduleDateType.attr('viewType');
            elem.find('span[act=scheduleDateType]').removeClass('active');
            if(!scheduleDateType.hasClass('active'))
                scheduleDateType.addClass('active');
            if ('day' == viewType) {
                elem.find("div[act=dayheader]").show();

                //if(isForceLoad == undefined || fromTab != viewType) {
                if(userChange == undefined) {
                    if (fixedDate != undefined) {
                        tabDate = moment(fixedDate);
                        me._setDayHead(fixedDate);
                        fromTab = "day";
                    } else {
                        if (fromTab == "week") {
                            //tabDate = moment(weekHead);
                            if(weekHead >= currSelWeek.start && weekHead <= currSelWeek.end){
                                tabDate = moment(weekHead);
                            } else {
                                tabDate = moment(currSelWeek.start);
                            }
                        } else if (fromTab == "month") {
                            //tabDate = moment(monthHead);
                            tabDate = moment(currSelMonth.start);
                        } else if (fromTab != viewType) {
                            tabDate = moment(me.$currentTimeMillis - 0);
                        }
                    }
                    elem.find('div[act=scheduleDateContainer]').html('<div act="scheduleDatePicker"></div>');
                    var $scheduleDatePicker = elem.find('div[act=scheduleDatePicker]');
                    $scheduleDatePicker.datepicker({
                        showOtherMonths: true,
                        selectOtherMonths: true,
                        changeMonth: false,
                        changeYear: false,
                        defaultDate: new Date(tabDate),
                        dayNamesMin: [ rk.i18n('SCHEDULE_SUNDAY'), rk.i18n('SCHEDULE_MONDAY'), rk.i18n('SCHEDULE_TUESDAY'), rk.i18n('SCHEDULE_WEDNESDAY'), rk.i18n('SCHEDULE_THURSDAY'), rk.i18n('SCHEDULE_FRIDAY'), rk.i18n('SCHEDULE_SATURDAY') ],
                        onSelect: function (dateText, inst) {
                            var mom = moment(dateText);
                            mom.add(1, 'day');
                            //alert(dateText + '至' + mom.format('YYYY-MM-DD'));
                            me._refreshFullcalendar('day', dateText);
                            //点击日期后会刷新日历？
                            /*me._delay(function () {
                                $scheduleDatePicker.datepicker('mark', me._$scheduleDate);
                            });*/

                            me._setDayHead(dateText);

                            setTimeout(function(){
                                $scheduleDatePicker.datepicker('mark', me._$scheduleDate);
                            }, 1);
                        },
                        onChangeMonthYear: function (year, month, inst) {
                            me._delay(function () {
                                me._loadDayData();
                            });

                            var dateText;
                            if(month < 10){
                                dateText = year + "-0" + month + "-01";
                            } else {
                                dateText = year + "-" + month + "-01";
                            }
                            me._setDayHead(dateText);

                            if(currSelDay != "" && scheduleService.calendarIsOpen()) {
                                setTimeout(function(){
                                    var temp;
                                    if(month == "1")
                                        temp = 12;
                                    else
                                        temp = parseInt(month) - 1;
                                    var tdmonth = elem.find("td[data-month=" + temp + "]").first();
                                    tdmonth.find("a").click();
                                }, 1);

                            }
                        }
                    });

                    if (fixedDate != undefined) {
                        me._setDayHead(fixedDate);
                        dayHead = fixedDate;
                    } else {
                        //if(isForceLoad != undefined || fixedDate != undefined || userChange != undefined || noReloadLeft != undefined){
                            me._setDayHead();
                        /*} else {
                            me._setDayHead(dayHead);
                        }*/
                    }
                }

                //加载日tab页
                me._loadDayData();

                if(noReloadLeft == undefined) {
                    if (currSelDay != ""){
                        if(scheduleService.calendarIsOpen()) {
                            //刷新左边日程页
                            me._refreshFullcalendar(viewType, currSelDay);
                        }
                    }
                }

                me._setDayViewYearMonth();

                fromTab = "day";
            } else if ('week' == viewType) {
                //将dayhead隐藏掉
                elem.find("div[act=dayheader]").hide();
                //if(isForceLoad == undefined || fromTab != viewType) {
                if(userChange == undefined) {
                    if (fixedDate != undefined) {
                        tabDate = moment(fixedDate);
                        me._setDayHead(fixedDate);
                        fromTab = "day";
                    } else {
                        if (fromTab == "day") {
                            //表明是从日切换到周
                            tabDate = moment(dayHead);
                        } else if (fromTab == "month") {
                            //表明是从月切换到周
                            //tabDate = moment(monthHead);
                            tabDate = moment(currSelMonth.start);
                        } else if (fromTab != viewType) {
                            tabDate = moment(me.$currentTimeMillis - 0);
                        }
                    }
                    var data = {};
                    data.currentYear = tabDate.get('year');
                    data.currentMonth = tabDate.get('month') + 1;
                    var startMoment = me._getStartMomentForWeek(data.currentYear, data.currentMonth);
                    var endMoment = me._getEndMomentForWeek(data.currentYear, data.currentMonth);
                    data.dates = me._getDatesForWeek(startMoment, endMoment);
                    elem.find('div[act=scheduleDateContainer]').html(rk.templateText(require('oa/tmpl/schedule/tpl_schedule_panel_type_week.tpl'), data));

                    if (fixedDate != undefined) {
                        //currSelWeek.start = fixedDate;
                        weekHead = fixedDate;
                    } else {
                        //if(isForceLoad != undefined || fixedDate != undefined || userChange != undefined || noReloadLeft != undefined)
                            weekHead = me._getWeekMonthHead();
                    }
                }

                //从日切换到周可以走通了
                //if(currSelWeek != "" && scheduleService.calendarIsOpen()) {
                if(currSelWeek != "") {
                    dateText = me._setCheckItem(currSelWeek.start);

                    if(scheduleService.calendarIsOpen()) {
                        if (noReloadLeft == undefined) {
                            //刷新左边日程页
                            me._refreshFullcalendar(viewType, dateText);
                        }
                    }
                }

                fromTab = "week";
            } else if ('month' == viewType) {
                elem.find("div[act=dayheader]").hide();
                //if(isForceLoad == undefined || fromTab != viewType) {
                if(userChange == undefined) {
                    if (fixedDate != undefined) {
                        tabDate = moment(fixedDate);
                        me._setDayHead(fixedDate);
                        fromTab = "day";
                    } else {
                        if (fromTab == "day") {
                            //表明是从日切换到月
                            tabDate = moment(dayHead);
                        } else if (fromTab == "week") {
                            //表明是从周切换到月
                            tabDate = moment(weekHead);
                        } else if (fromTab != viewType) {
                            tabDate = moment(me.$currentTimeMillis - 0);
                        }
                    }
                    var data = {};
                    data.currentYear = tabDate.get('year');
                    data.currentMonth = tabDate.get('month') + 1;
                    data.dates = me._getDatesForMonth(data.currentYear, data.currentMonth);
                    elem.find('div[act=scheduleDateContainer]').html(rk.templateText(require('oa/tmpl/schedule/tpl_schedule_panel_type_month.tpl'), data));
                    dateText = data.currentYear + "-" + data.currentMonth + "-01";

                    //}

                    if (fixedDate != undefined) {
                        //currSelMonth.start = fixedDate;
                        monthHead = fixedDate;
                    } else {
                        //if(isForceLoad != undefined || fixedDate != undefined || userChange != undefined || noReloadLeft != undefined)
                            monthHead = me._getWeekMonthHead();
                    }
                }

                //从日切换到月可以走通了
                //if(currSelMonth != "" && scheduleService.calendarIsOpen()) {
                if(currSelMonth != "") {
                    dateText = me._setCheckItem(currSelMonth.start);

                    if(scheduleService.calendarIsOpen()) {
                        if (noReloadLeft == undefined) {
                            //刷新左边日程页
                            me._refreshFullcalendar(viewType, dateText);
                        }
                    }
                }

                fromTab = "month";
            }

            ////刷新左边日程页
            //me._refreshFullcalendar(viewType, dateText);
        },
        _setDayViewYearMonth: function (){
            var elem = this.element;
            var year = elem.find("span[class=ui-datepicker-year]:eq(0)").text();
            var month = elem.find("span[class=ui-datepicker-month]:eq(0)").text();
            elem.find("span[act=headyear]:eq(0)").text(year + rk.i18n('SCHEDULE_YEAR'));
            elem.find("span[act=headmonth]:eq(0)").text(month);

        },
        _setCheckItem: function (oneDay) {
            var elem = this.element;
            var $span = elem.find('span[startv=' + oneDay + ']');
            $span.addClass('active-month');
            var viewType = $span.attr('viewType'),
                startV = $span.attr('startV'),
                endV = $span.attr('endV');
            return startV;
        },
        _getWeekMonthHead: function(){
            var elem = this.element;
            var year = elem.find('span[class=date-year]').eq(1).attr("yearval");
            var month = elem.find('span[class=date-month]').eq(1).attr("monthval");
            if(month < 10){
                return year + "-0" + month + "-01";
            } else {
                return year + "-" + month + "-01";
            }
        },
        _setDayHead:function (dateText) {
            if(dateText == undefined) {
                var $scheduleDatePicker = this.element.find('div[act=scheduleDatePicker]');
                var selDate = $scheduleDatePicker.datepicker("getDate");
                var mom = moment(selDate);
                dayHead = mom.format('YYYY-MM-DD');
                currSelDay = dayHead;
            } else{
                var mom = moment(dateText);
                dayHead = mom.format('YYYY-MM-DD');
                currSelDay = dayHead;
            }
        },
        _refreshFullcalendar: function(viewType, dateText){
            var me = this;
            scheduleService.showFullcalendar(viewType, dateText);
            if(viewType == "day"){
                me._setPreClickDay(dateText);
            } else if(viewType == "week"){
                me._setPreClickDayWeek(dateText);
            } else if(viewType == "month"){
                me._setPreClickDayMonth(dateText);
            }
        },
        _bindHandler: function() {
            var me = this;
            var elem = me.element;

            var header = me.getPanelHeader();
            var isIndustry = SESSION.tenantType;
            if(isIndustry != 1){//判断是否是行业版
                header.find('a[act="createSchedule"]').click($.proxy(me._handleCreateClick, me));
            }


            elem.on('click', 'a[act=scheduleCurtain]', function() {
                me._handleScheduleCurtainClick();
            });

            elem.on('click', 'a[act=datePre]', function () {
                var viewType = $(this).attr('viewType');
                if(viewType == "day") {
                    elem.find('a[data-handler=prev]').first().click();

                    me._setDayViewYearMonth();
                } else if (viewType == 'week') {
                    var $elYear = elem.find('span[yearVal]'),
                        $elMonth = elem.find('span[monthVal]');
                    var yearVal = $elYear.attr('yearVal'),
                        monthVal = $elMonth.attr('monthVal');
                    var mom = moment();
                    mom.year(yearVal);
                    mom.month(monthVal - 1);
                    mom.subtract(1, 'month');
                    var newYear = mom.get('year'),
                        newMonth = mom.get('month') + 1;
                    var startMoment = me._getStartMomentForWeek(newYear, newMonth);
                    var endMoment = me._getEndMomentForWeek(newYear, newMonth);
                    var date = {};
                    date.dates = me._getDatesForWeek(startMoment, endMoment);
                    elem.find('div.schedule-datepicker-body').html(rk.templateText(require('oa/tmpl/schedule/tpl_schedule_panel_type_week_include.tpl'), date));
                    $elYear.attr('yearVal', newYear);
                    $elMonth.attr('monthVal', newMonth);
                    $elYear.html(newYear + rk.i18n('SCHEDULE_YEAR'));
                    $elMonth.html(newMonth + rk.i18n('SCHEDULE_MONTH_DAY'));

                    weekHead = me._getWeekMonthHead();
                    if(weekHead && scheduleService.calendarIsOpen()) {
                        me._setCheckItem(currSelWeek.start);
                        //刷新左边日程页
                        me._refreshFullcalendar(viewType, weekHead);
                    }
                } else if (viewType == 'month') {
                    var $elYear = elem.find('span[yearVal]'),
                        $elMonth = elem.find('span[monthVal]');
                    var yearVal = $elYear.attr('yearVal'),
                        monthVal = $elMonth.attr('monthVal');
                    var mom = moment();
                    mom.year(yearVal);
                    mom.month(monthVal - 1);
                    mom.subtract(6, 'month');
                    var newYear = mom.get('year'),
                        newMonth = mom.get('month') + 1;
                    var date = {};
                    date.dates = me._getDatesForMonth(newYear, newMonth);
                    elem.find('div.schedule-datepicker-body').html(rk.templateText(require('oa/tmpl/schedule/tpl_schedule_panel_type_month_include.tpl'), date));
                    $elYear.attr('yearVal', newYear);
                    $elMonth.attr('monthVal', newMonth);
                    $elYear.html(newYear + rk.i18n('SCHEDULE_YEAR'));
                    $elMonth.html(newMonth <= 6 ?rk.i18n('SCHEDULE_1HALF_YEAR') :rk.i18n('SCHEDULE_2HALF_YEAR'));

                    monthHead = me._getWeekMonthHead();
                    if(monthHead && scheduleService.calendarIsOpen()) {
                        me._setCheckItem(currSelMonth.start);
                        //刷新左边日程页
                        me._refreshFullcalendar(viewType, monthHead);
                    }
                }
            });

            elem.on('click', 'a[act=dateNext]', function () {
                var viewType = $(this).attr('viewType');
                if(viewType == "day") {
                    elem.find('a[data-handler=next]').first().click();
                    me._setDayViewYearMonth();
                } else if (viewType == 'week') {
                    var $elYear = elem.find('span[yearVal]'),
                        $elMonth = elem.find('span[monthVal]');
                    var yearVal = $elYear.attr('yearVal'),
                        monthVal = $elMonth.attr('monthVal');
                    var mom = moment();
                    mom.year(yearVal);
                    mom.month(monthVal - 1);
                    mom.add(1, 'month');
                    var newYear = mom.get('year'),
                        newMonth = mom.get('month') + 1;
                    var startMoment = me._getStartMomentForWeek(newYear, newMonth);
                    var endMoment = me._getEndMomentForWeek(newYear, newMonth);
                    var date = {};
                    date.dates = me._getDatesForWeek(startMoment, endMoment);
                    elem.find('div.schedule-datepicker-body').html(rk.templateText(require('oa/tmpl/schedule/tpl_schedule_panel_type_week_include.tpl'), date));
                    $elYear.attr('yearVal', newYear);
                    $elMonth.attr('monthVal', newMonth);
                    $elYear.html(newYear + rk.i18n('SCHEDULE_YEAR'));
                    $elMonth.html(newMonth + rk.i18n('SCHEDULE_MONTH_DAY'));

                    weekHead = me._getWeekMonthHead();
                    if(weekHead && scheduleService.calendarIsOpen()) {
                        me._setCheckItem(currSelWeek.start);
                        //刷新左边日程页
                        me._refreshFullcalendar(viewType, weekHead);
                    }
                } else if (viewType == 'month') {
                    var $elYear = elem.find('span[yearVal]'),
                        $elMonth = elem.find('span[monthVal]');
                    var yearVal = $elYear.attr('yearVal'),
                        monthVal = $elMonth.attr('monthVal');
                    var mom = moment();
                    mom.year(yearVal);
                    mom.month(monthVal - 1);
                    mom.add(6, 'month');
                    var newYear = mom.get('year'),
                        newMonth = mom.get('month') + 1;
                    var date = {};
                    date.dates = me._getDatesForMonth(newYear, newMonth);
                    elem.find('div.schedule-datepicker-body').html(rk.templateText(require('oa/tmpl/schedule/tpl_schedule_panel_type_month_include.tpl'), date));
                    $elYear.attr('yearVal', newYear);
                    $elMonth.attr('monthVal', newMonth);
                    $elYear.html(newYear + rk.i18n('SCHEDULE_YEAR'));
                    $elMonth.html(newMonth <= 6 ?rk.i18n('SCHEDULE_1HALF_YEAR') :rk.i18n('SCHEDULE_2HALF_YEAR'));

                    monthHead = me._getWeekMonthHead();
                    if(monthHead && scheduleService.calendarIsOpen()) {
                        me._setCheckItem(currSelMonth.start);
                        //刷新左边日程页
                        me._refreshFullcalendar(viewType, monthHead);
                    }
                }
            });

            elem.on('click', 'li.js-select-date', function (evt) {
                //me._weekMonthSelect();
                elem.find('span.active-month').removeClass('active-month');
                var $el = $(this), $span = $el.find('span.digit-month').addClass('active-month');
                var viewType = $span.attr('viewType'),
                    startV = $span.attr('startV'),
                    endV = $span.attr('endV');
                //alert(startV + '至' + endV);
                me._refreshFullcalendar(viewType, startV);
                if(viewType == "week"){
                    weekHead = startV;
                    currSelWeek.start = startV;
                } else if(viewType == "month"){
                    monthHead = startV;
                    currSelMonth.start = startV;
                }
            });

            elem.on('click', 'span[act=scheduleDateType]', function() {
                me._renderCalender($(this));
            });
            //todo 此处需要改成上一次点击过的日期类型
            //elem.find('span[act=scheduleDateType]').eq(0).trigger('click');
        },
        //用于左边日程页返回本日、本周、本月
        //export function
        gotoToday: function () {
            var me = this;
            var elem = this.element;
            var mom = moment(me.$currentTimeMillis - 0);

            var active = 0;
            var scheduleDateTypes = elem.find('span[act=scheduleDateType]');
            for (var i in scheduleDateTypes) {
                if (scheduleDateTypes.eq(i).hasClass('active')) {
                    //active = i;
                    me._renderCalender(scheduleDateTypes.eq(i), true, mom.format('YYYY-MM-DD'));
                    break;
                }
            }
        },
        //用于左边翻页时刷新右边日历页
        //export function
        goto: function (view, firstday){
            var me = this;
            var today = moment(me.$currentTimeMillis - 0).format('YYYY-MM-DD');

            var elem = this.element;
            var scheduleDateTypes = elem.find('span[act=scheduleDateType]');

            if(view == "day") {
                var year = moment(preClickDay).year();
                //var month = moment(preClickDay).month();
                var day = moment(preClickDay).date();
                var tdmonth = elem.find("td[data-year=" + parseInt(year) + "]");

                tdmonth.each(function (i, td) {
                    var aItem = $(td).find('a');
                    if (aItem.hasClass("ui-state-active"))
                        aItem.removeClass("ui-state-active");
                });

                //month = moment(firstday).month();
                year = moment(preClickDay).year();
                day = moment(firstday).date();
                tdmonth = elem.find("td[data-month=" + parseInt(year) + "]");

                var isReloadCalLocal = true;

                tdmonth.each(function (i, td){
                    var aItem = $(td).find('a');
                    if(aItem.hasClass("ui-state-active"))
                        aItem.removeClass("ui-state-active");
                    if(aItem.html() == day){
                        isReloadCalLocal = false;
                        //aItem.click();

                        //不加载日历，只记录当前操作的日期，用于替代原来的onclick事件
                        var mom = moment(firstday);
                        mom.add(1, 'day');
                        me._setDayHead(firstday);

                        if(!aItem.hasClass("ui-state-active"))
                            aItem.addClass("ui-state-active");
                        return false;
                    }
                });

                if (preClickDay != undefined) {
                    if(preClickDay == firstday)
                        return;
                } else {
                    me._setPreClickDay(today);
                }

                if(isReloadCalLocal) {
                    me._renderCalender(scheduleDateTypes.eq(0), true, firstday, undefined, true);
                }
            } else if(view == "week") {
                var noReloadLender = false;
                var $span = elem.find('span[startv=' + firstday + ']');
                if($span.size() > 0) {
                    //查找viewtype=week的，全部清除掉样式
                    var weeks = elem.find("span[viewtype=week]");
                    weeks.removeClass("active-month");
                    /*for(var i in weeks){
                        if(weeks.eq(i).hasClass("active-month")){
                            weeks.eq(i).removeClass("active-month");
                        }
                    }*/

                    $span.addClass('active-month');
                    noReloadLender = true;

                    weekHead = firstday;
                    currSelWeek.start = firstday;
                    me._setPreClickDayWeek(firstday);
                }

                if (preClickDayWeek != undefined) {
                    if(preClickDayWeek == firstday)
                        return;
                } else {
                    me._setPreClickDayWeek(today);
                }

                if(!noReloadLender)
                    me._renderCalender(scheduleDateTypes.eq(1), true, firstday, undefined, true);
            } else if(view == "month") {
                var noReloadLender = false;
                var $span = elem.find('span[startv=' + firstday + ']');
                if($span.size() > 0) {
                    //查找viewtype=month的，全部清除掉样式
                    var months = elem.find("span[viewtype=month]");
                    months.removeClass("active-month");

                    $span.addClass('active-month');
                    noReloadLender = true;

                    monthHead = firstday;
                    currSelMonth.start = firstday;
                    me._setPreClickDayMonth(firstday);
                }

                if (preClickDayMonth != undefined) {
                    if(preClickDayMonth == firstday)
                        return;
                } else {
                    me._setPreClickDayMonth(today);
                }

                if(!noReloadLender)
                    me._renderCalender(scheduleDateTypes.eq(2), true, firstday, undefined, true);
            }
        },
        _setPreClickDay: function (dateText){
            preClickDay = dateText;
        },
        setPreClickDay:function (dateText){
            preClickDay = dateText;
        },
        _setPreClickDayWeek: function (dateText){
            preClickDayWeek = dateText;
        },
        setPreClickDayWeek: function (dateText){
            preClickDayWeek = dateText;
        },
        _setPreClickDayMonth: function (dateText){
            preClickDayMonth = dateText;
        },
        setPreClickDayMonth: function (dateText){
            preClickDayMonth = dateText;
        },
        _getDatesForMonth: function (year, month) {
            var match = false;
            var me = this;
            var elem = me.element;
            if (month <= 6) {
                month = 1;
            } else {
                month = 7;
            }
            var startMoment = moment();
            startMoment.year(year);
            startMoment.month(month - 1);
            startMoment.date(1);
            var dates = [];
            var now = moment(me.$currentTimeMillis);
            for (var i = 0; i < 6; i++) {
                var dateV = {};
                var currentFlg = 1;
                dateV.start = startMoment.format('YYYY-MM-DD');
                dateV.text = startMoment.format('MM'+rk.i18n('SCHEDULE_MONTH_DAY'));
                if (now.diff(startMoment) < 0) {
                    currentFlg = 0;
                }
                startMoment.add(1, 'month');
                if (now.diff(startMoment) > 0) {
                    currentFlg = 0;
                }
                dateV.currentFlg = currentFlg;
                dateV.end = startMoment.format('YYYY-MM-DD');

                //如果显示的日期位于本区间，则设置应该自动选择的区间
                if(fromTab == "day") {
                    if (currSelDay != "" && moment(currSelDay).add(1, 'day').format('YYYY-MM-DD') >= dateV.start && moment(currSelDay).add(1, 'day').format('YYYY-MM-DD') <= dateV.end) {
                        currSelMonth = dateV;
                        me._setDayHead(dateV.start);
                        match = true;
                    }
                } else if(fromTab == "week") {
                    if(weekHead != "" && weekHead >= dateV.start && weekHead < dateV.end){
                        currSelMonth = dateV;
                        //currSelWeek = "";
                        //weekHead = "";
                        me._setDayHead(dateV.start);
                        match = true;
                    }
                }
                /*//if(currSelWeek != "" && currSelWeek.start >= dateV.start && currSelWeek.end <= dateV.end){
                if(weekHead != "" && weekHead >= dateV.start && weekHead < dateV.end){
                    currSelMonth = dateV;
                    //currSelWeek = "";
                    //weekHead = "";
                    //currSelDay = dateV.start;
                }
                if(currSelWeek != "" && currSelWeek.start >= dateV.start && currSelWeek.end <= dateV.end){
                    currSelMonth = dateV;
                    //currSelWeek = "";
                    //currSelDay = dateV.start;
                }*/
                dates.push(dateV);
            }

            if(match == false){
                currSelMonth = dates[0];
                me._setDayHead(dates[0].start);
                currSelWeek = dates[0];
            }

            return dates;
        },
        _getDatesForWeek: function (startMoment, endMoment) {
            match = false;
            var me = this;
            var elem = me.element;
            var dates = [];
            var now = moment(me.$currentTimeMillis);
            while (startMoment.diff(endMoment) <= 0) {
                var dateV = {};
                var dateText = '';
                var currentFlg = 1;
                dateV.start = startMoment.format('YYYY-MM-DD');
                dateText = startMoment.format('MM' + rk.i18n('SCHEDULE_MONTH_HIDE') + 'DD' + rk.i18n('SCHEDULE_DAY_HIDE'));
                dateText += ' - ';
                if (now.diff(startMoment) < 0) {
                    currentFlg = 0;
                }
                startMoment.add(6, 'day');
                dateText += startMoment.format('MM' + rk.i18n('SCHEDULE_MONTH_HIDE') + 'DD' + rk.i18n('SCHEDULE_DAY_HIDE'));
                dateV.text = dateText;
                if (now.diff(startMoment) > 0) {
                    currentFlg = 0;
                }
                dateV.currentFlg = currentFlg;
                startMoment.add(1, 'day');
                dateV.end = startMoment.format('YYYY-MM-DD');

                //如果显示的日期位于本区间，则设置应该自动选择的区间
                if(fromTab == "day"){
                    if(currSelDay != "" && moment(currSelDay).add(1, 'day').format('YYYY-MM-DD') >= dateV.start && moment(currSelDay).add(1, 'day').format('YYYY-MM-DD') <= dateV.end){
                        currSelWeek = dateV;
                        me._setDayHead(dateV.start);
                        currSelMonth = dateV;
                        match = true;
                    }
                } else if(fromTab == "month") {
                    if (currSelMonth != "" && currSelMonth.start >= dateV.start && currSelMonth.start <= dateV.end) {
                        currSelWeek = dateV;
                        //currSelMonth = "";
                        me._setDayHead(dateV.start);
                        match = true;
                    }
                }
                dates.push(dateV);
            }

            if(match == false){
                currSelWeek = dates[0];
                me._setDayHead(dates[0].start);
                currSelMonth = dates[0];
            }

            return dates;
        },
        _getStartMomentForWeek: function (year, month) {
            var mom = moment();
            mom.year(year);
            mom.month(month - 1);
            mom.date(1);
            var dayOfWeek = mom.day();
            if (dayOfWeek == 0) {
                dayOfWeek = 7;
            }
            if (dayOfWeek == 1) {
                return mom;
            } else {
                return mom.subtract(dayOfWeek, 'day').add(1, 'day');
            }
        },
        _getEndMomentForWeek: function (year, month) {
            var mom = moment();
            mom.year(year);
            mom.month(month - 1);
            mom.date(1);
            mom.add(1, 'month');
            mom.subtract(1, 'day');
            var dayOfWeek = mom.day();
            if (dayOfWeek == 0) {
                dayOfWeek = 7;
            }
            if (dayOfWeek == 7) {
                return mom;
            } else {
                return mom.add(7, 'day').subtract(dayOfWeek, 'day');
            }
        },
        //_loadDayData: function (startDate, endDate) {
        _loadDayData: function () {
            var me = this;
            var elem = me.element;
            var $scheduleDatePicker = elem.find('div[act=scheduleDatePicker]');
            var inst = $scheduleDatePicker.data("datepicker");
            rk.post('/json/crm_schedule/count-by-day.action', {
                startDate: moment(inst.firstDate).format('YYYY-MM-DD'),
                endDate: moment(inst.lastDate).format('YYYY-MM-DD'),
                showTask: 1,
                isFinish: 1,
                userId: userId
            }).done(function (json) {
                if (json.status == 0) {
                    var dateArray = [];
                    $.each($.parseJSON(json.data), function (key, value) {
                        dateArray.push(new Date(key));
                    });
                    me._$scheduleDate = dateArray;
                    $scheduleDatePicker.datepicker('mark', dateArray);
                } else {
                    $.msg(rk.i18n('LOAD_ERROR'));
                }
            });
        },
        _handleScheduleCurtainClick: function() {
            var me = this;
            var elem = this.element;
            rk.oa.popupCurtain({
                onSuccess: function(curtainElem) {
                    curtainElem.scheduleCurtainCtrl();
                }
            });
        },
        //_handleRowClick: function (row) {
        //    var me = this;
        //    var elem = me.element;
        //    var applyId = row.attr('applyId');
        //    var approvalUserId = row.attr('approvalUserId');
        //    $('div[applyId]').removeClass('show-content-hover');
        //    row.addClass('show-content-hover');
        //    me.popupContent({
        //        onSuccess: function (contentElem) {
        //            contentElem.approvalContentCtrl({
        //                applyId: applyId,
        //                approvalUserId: approvalUserId
        //            });
        //        }
        //    });
        //},
        _handleCreateClick: function(type) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var defaultCreate = function() {
                var start = moment(me.$currentTimeMillis - 0);
                start.set('minutes', 0);
                start.set('second', 0);
                start.add(60, 'minutes');
                var end = moment(+start.toDate() + 30 * 60 * 1000)
                var opt = {
                    startDate: start.format('YYYY-MM-DD'),
                    startTime: start.format('HH:mm:ss'),
                    endDate: end.format('YYYY-MM-DD'),
                    endTime: end.format('HH:mm:ss'),
                    isAllDay: false,
                    act: 'create',
                    ownerUser: SESSION.user
                };
                var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil')
                scheduleUtil.popupEditor(opt);
            };
            if(type == "visit_schedule"){//巡访计划
                rk.dialog({
                    title: rk.i18n('PAGE_NEW_VISIT'),
                    //width:"930",
                    success: function (contentElem) {
                        require.async(["./visit/visitPlanCreateDialogCtrl"],function(){
                            contentElem.visitPlanCreateDialogCtrl();//初始化弹框内容的Ctrl
                        });

                    },
                    footer: ['cancel', {
                        act: 'ok', visible: true, text: rk.i18n('SAVE')
                    }]
                });
            }else if(type == "default_schedule"){
                defaultCreate();
            }else{
                defaultCreate();
            }
        }
    });

    return $;
});
